#include "FileSort.h"
#include <algorithm>

// 比较函数的定义
bool FileSort::compareByTime(const FileTime& a, const FileTime& b) {
    return a.time < b.time;
}

// 处理文件的函数定义
std::vector<std::string> FileSort::processFiles(const std::string& path) {
    std::vector<FileTime> fileTimes;
    int validFileCount = 0;

    // 遍历指定文件夹中的所有文件
    try {
        for (const auto& entry : fs::directory_iterator(path)) {
            if (entry.is_regular_file()) {
                std::string filename = entry.path().filename().string();
                // 检查文件名是否以 "result " 开头，以 ".s.dat" 结尾
                if (filename.find("result ") == 0 && filename.find("s.dat") != std::string::npos) {
                    validFileCount++;
                    // 提取时间值
                    size_t startPos = filename.find("result ") + 7;
                    size_t endPos = filename.find("s.dat");
                    std::string timeStr = filename.substr(startPos, endPos - startPos);
                    double time;
                    try {
                        time = std::stod(timeStr);
                        fileTimes.push_back({filename, time});
                    } catch (const std::invalid_argument& e) {
                        std::cerr << "Invalid time format in file: " << filename << ", time string: " << timeStr << std::endl;
                        system("pause");
                    }
                }
            }
        }
    } catch (const fs::filesystem_error& e) {
        std::cerr << "fielSys Error:" << e.what() << std::endl;
        system("pause");
    }

    std::cout << "result*.dat->count = " << validFileCount << std::endl;

    // 按时间值对文件进行排序
    std::sort(fileTimes.begin(), fileTimes.end(), compareByTime);

    // 将排序后的文件名存储到 vector 中
    std::vector<std::string> sortedFilenames;
    for (const auto& ft : fileTimes) {
        sortedFilenames.push_back(ft.filename);
    }

    return sortedFilenames;
}
